import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Select, Icon, Button, Dropdown, Menu, InputNumber, DatePicker, Modal, message, Radio} from 'antd';
import RecommendResultTable from '../../../components/Huishuaka/Config/RecommendResult';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';

import styles from './RecommendResult.less';

let isAdd = true;
const FormItem = Form.Item;
const smartTypes = RecommendResultTable.smartTypes
const { Option } = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(({ recommendResult, loading }) => ({
  recommendResult,
  loading: loading.models.recommendResult,
}))
@Form.create()
export default class RecommendResultList extends PureComponent {
  state = {
    addInputValue: {},
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'recommendResult/fetch',
    });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'recommendResult/fetch',
      payload: params,
    });
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'recommendResult/fetch',
      payload: {},
    });
  }

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  }

  deleteSelectClick = () => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    const that = this;

    Modal.confirm({
      title: '删除警告!',
      content: '确认删除所选内容？',
      onOk() {
        dispatch({
          type: 'recommendResult/remove',
          payload: {
            types: `${selectedRows.map(row => row.type).join(',')},`,
          },
          callback: () => {
            that.setState({
              selectedRows: [],
            });
          },
        });
      },
      onCancel() {
        // alert(JSON.stringify(selectedRows));
      },
    });
  }

  handleMenuClick = (e) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'recommendResult/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  }

  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  }

  handleSearch = (e) => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'recommendResult/fetch',
        payload: values,
      });
    });
  }

  addOne = () => {
    this.clearForm();
    isAdd = true;
    this.handleModalVisible(true);
  }

  clearForm = () => {
    if (!isAdd) { // 清除表单内容
      this.state.addInputValue = {}; // 清除上一次加载的行数据——阻止编辑时的数据进入新增页面表单
      this.props.form.resetFields(); // 清除当前表单的数据——阻止编辑时未存储的数据进入1个新的编辑页
    }
  }

  handleModalVisible = (flag) => {
    this.setState({
      modalVisible: !!flag,
    });
  }

  // 通过代理对象传入控件value
  handleAddInput = (e) => {
    let key = e.target.id;
    if (!key) {
      key = e.target.name;
    }
    this.state.addInputValue[key] = e.target.value;
  }

  // 直接传入控件value
  addInputNumber = (val) => {
    this.state.addInputValue.smart_order = val;
  }
  addInputSelect = (val) => {
    this.state.addInputValue.smart_property = val;
  }

  // 修改
  modifyOne = (row) => {
    this.clearForm();
    isAdd = false;
    this.state.addInputValue = JSON.parse(JSON.stringify(row));// 防止传递引用
    this.handleModalVisible(true);
  }

  handleAdd = () => {
    this.props.dispatch({
      type: 'recommendResult/add',
      payload: {
        params: this.state.addInputValue,
      },
    });

    message.success('添加成功');
    this.setState({
      modalVisible: false,
    });
    this.state.addInputValue = {};
  }

  render() {
    const { recommendResult: { data }, loading } = this.props;
    const { selectedRows, modalVisible } = this.state;
    const { getFieldDecorator, validateFieldsAndScroll } = this.props.form;

    const validate = () => {
      validateFieldsAndScroll((error) => {
        if (!error) {
          // submit the values
          this.handleAdd();
        }
      });
    };

    return (
      <PageHeaderLayout title="智能推荐结果设置">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.addOne()}>
                新建
              </Button>
              {
                selectedRows.length > 0 && (
                  <span>
                    <Button onClick={this.deleteSelectClick}>批量删除</Button>
                    {/* <Dropdown overlay={menu}>
                      <Button>
                        更多操作 <Icon type="down" />
                      </Button>
                    </Dropdown> */}
                  </span>
                )
              }
            </div>
            <RecommendResultTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              modifyOne={this.modifyOne}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <Modal
          title="添加智能推荐结果配置"
          visible={modalVisible}
          onOk={validate}
          onCancel={() => this.handleModalVisible()}
        >
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="结果类型"
          >
            {getFieldDecorator('type', {
              initialValue: this.state.addInputValue.type,
              rules: [
                {
                  required: true,
                  message: '这是一个必填项！',
                },
              ],
            })(
              <Select
                id="type"
                onSelect={this.addInputSelect}
                placeholder="不限"
                defaultValue={this.state.addInputValue.type}
                style={{ maxWidth: 200, width: '100%' }}
              >
                {
                  smartTypes.map(type =>
                    <Option value={type.value}>{type.text}</Option>
                  )
                }
              </Select>
            )}
          </FormItem>
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="匹配度"
          >
            {getFieldDecorator('matchPercent', {
              initialValue: this.state.addInputValue.matchPercent,
              rules: [
                {
                  required: true,
                  message: '这是一个必填项！',
                },
              ],
            })(
              <Input placeholder="匹配度" id="matchPercent" onChange={this.handleAddInput} />
            )}
          </FormItem>
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="描述"
          >
            {getFieldDecorator('desc', {
              initialValue: this.state.addInputValue.desc,
              rules: [
                {
                  required: true,
                  message: '这是一个必填项！',
                },
              ],
            })(
              <Input placeholder="描述" id="desc" onChange={this.handleAddInput} />
            )}
          </FormItem>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
